/*
 * Copyright (c) 2023-9-2
 * 说明: 教练绑定的学员信息
 */

package client

import (
	"context"
	serverCommon "fiberCommonUtils/common"
	"github.com/gofiber/fiber/v2"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"mongoDB"
)

type StudentInfo struct {
	ID       primitive.ObjectID `bson:"_id,omitempty" json:"id"`
	Name     string             `json:"name" bson:"name"`
	Phone    string             `json:"phone" bson:"phone"`
	IdNumber string             `json:"idNumber" bson:"id_number"`
	CoachID  primitive.ObjectID `json:"-" bson:"coach_id"`
}

func (i *StudentInfo) Save(ctx context.Context) (*mongo.UpdateResult, error) {
	if i.ID.IsZero() {
		i.ID = primitive.NewObjectID()
	}
	id, err := (&mongo.Collection{}).UpdateByID(
		ctx,
		i.ID,
		bson.D{
			{"$set", i},
		},
		options.Update().SetUpsert(true),
	)
	return id, err
}

func TotalNumberOfCoachSStudent(c *fiber.Ctx) error {
	ctx, cancel := mongoDB.MongoDBTimeoutContext()
	defer cancel()
	cid := c.Locals("clientID").(primitive.ObjectID)
	count, err := (&mongo.Collection{}).CountDocuments(
		ctx,
		bson.D{
			{"coach_id", cid},
		},
	)
	if err != nil {
		return err
	}
	return c.JSON(serverCommon.MakeSuccessJson(count))
}

func CoachReadHisStudents(c *fiber.Ctx) error {
	ctx, cancel := mongoDB.MongoDBTimeoutContext()
	defer cancel()
	cid := c.Locals("clientID").(primitive.ObjectID)
	cursor, err := (&mongo.Collection{}).Find(
		ctx,
		bson.D{
			{"coach_id", cid},
		},
	)
	studentRecords, err := _decodeManyStudentRecord(cursor, err, ctx)
	if err != nil {
		return err
	}
	return c.JSON(serverCommon.MakeSuccessJson(studentRecords))
}

func _decodeManyStudentRecord(cursor *mongo.Cursor, queryErr error, ctx context.Context) (clientOne *[]StudentInfo, err error) {
	if queryErr != nil {
		return nil, queryErr
	}
	result := make([]StudentInfo, 0)
	err = cursor.All(ctx, &result)
	if err != nil {
		return nil, err
	}
	return &result, nil
}
